use super::Tomlable;

use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::Path;

#[derive(Debug, Serialize, Deserialize)]
pub struct DeviceConf {
  pub sn: String,
  pub keyboard: String,
  // width x height
  pub screen_size: [u32; 2],
  pub screen_density: u32,
}

impl DeviceConf {
  pub fn new(sn: String) -> Self {
    DeviceConf {
      sn,
      keyboard: String::from(""),
      screen_size: [0; 2],
      screen_density: 0,
    }
  }
}

impl<'a, P> Tomlable<'a, P> for DeviceConf
where
  P: AsRef<Path>,
{
  fn write_to_toml(&self, to_location: P, overridable: bool) -> io::Result<()> {
    let config_file = to_location.as_ref();
    if !config_file.exists() || overridable {
      let action = iif!(!overridable, "创建", "覆盖");
      println!("{}device配置文件...", action);
      let toml = toml::to_string(self).unwrap();
      if let Ok(_) = fs::write(config_file, toml) {
        println!(
          "==成功{}device配置文件`{}`==",
          action,
          config_file.file_name().unwrap().to_str().unwrap()
        );
      } else {
        eprintln!("can't save .toml in the path<{}>", config_file.display());
      }
    } else {
      println!("==已检测到device配置文件,跳过==");
    }

    Ok(())
  }
  fn read_from_toml(from_location: P) -> io::Result<Self> {
    let content = fs::read_to_string(from_location.as_ref())?;
    let device_conf = toml::from_str::<Self>(&content);

    match device_conf {
      Ok(device_conf) => Ok(device_conf),
      Err(err) => {
        eprint!("err=>{}", err);
        panic!(
          "无法找到device配置文件<{}>",
          from_location.as_ref().display()
        );
      }
    }
  }
}
